package com.qingxin.sys.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.qingxin.sys.utils.StringUtils;

/**
 * 请求编码过滤器，过滤所有指定请求，将请求参数字符串转换为指定编码，避免乱码出现
 */
public class RequestEncodingFilter implements Filter {

	@Override
	public void destroy() {
	}

	//主过滤方法
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//仅当启用且编码不为空时进行处理
		if(!ignore && encoding!=null){
			HttpServletRequest request2 = (HttpServletRequest) request;
			request2.setCharacterEncoding(encoding);
			if ("GET".equalsIgnoreCase(request2.getMethod()) && request2.getQueryString() != null && filterGetMethod){
				//处理GET请求
				request = new RequestEncodingWrapper(request2, encoding);
			}
			
			if("POST".equalsIgnoreCase(request2.getMethod()) && request2.getQueryString() != null && filterPostQueryString){
				//处理POST请求
				request = new RequestEncodingPostWrapper(request2, encoding);
			}
			
			if(forceEncoding){
				//处理响应信息编码设置
				response.setCharacterEncoding(encoding);
			}
		}
		chain.doFilter(request, response);
		
	}
	
	
	//初始化方法
	@Override
	public void init(FilterConfig config) throws ServletException {
		encoding = config.getInitParameter("encoding");
		if(StringUtils.isEmpty(encoding)){
			encoding = null;
		}
		//是否忽略
		ignore = "true".equalsIgnoreCase(config.getInitParameter("ignore"));
		//是否处理GET请求
		filterGetMethod = !"false".equalsIgnoreCase(config.getInitParameter("filterGetMethod"));
		
		//是否处理POST请求的QueryString
		filterPostQueryString = !"false".equalsIgnoreCase(config.getInitParameter("filterPostQueryString"));
		
		//是否处理响应
		forceEncoding = !"false".equalsIgnoreCase(config.getInitParameter("forceEncoding"));
	}
	
	private String encoding = null;//字符编码
	private boolean ignore = false;//是否忽略，如果为true则过滤器不起作用
	private boolean filterGetMethod = true;//是否过滤GET请求，默认过滤
	private boolean filterPostQueryString = true;//是否过滤POST请求，默认过滤
	private boolean forceEncoding = true;//是否设置响应的编码，默认设置

}
